var mongoose = require('mongoose');
var User = require('../models/user.model')// 引数据模型

// 新增
exports.create = function(req,res,next){
    var user = new User(req.body); // 从req.body里获取参数对象，比如{name:'vane',gender:'男',city:'杭州'....}
    //user是表
    user.save()
    .then(data=>{
        res.json(data)
    })
    
}

//修改
exports.update = function(req,res,next){
  
    var id = req.params.id; // req.param('id')
    // 现在操作的都是mongoose而不是mongodb
    User.findByIdAndUpdate(id,{$set: req.body}, {new:false} )
    .then(data=>{
        res.json({msg:'数据修改成功',status:200}); // 如果你要返回数据，这个data返回的是你之前修改的那个数据内容
    })
}

//删除
exports.remove = function(req,res,next){
    var id = req.params.id;
    User.findByIdAndRemove(id,function(err,doc){
        res.json({msg:'数据删除成功',status:200})
    })
} 


exports.list = function(req,res,next){
    var page = (req.body.page) ? req.body.page : 1;
    var limit = (req.body.limit) ? req.body.limit : 2;
    //var rows = (req.body.limit) ? req.body.rows : 10;

    var queryCondition = {};
    var name;
    if( req.body.name && req.body.name.trim().length>0 ){
        name = req.body.name;
        queryCondition = {"name":new RegExp(name,'i')}
    }

    // User.paginate(queryCondition, { page: page, limit:parseInt(rows)}, function(err, result) {
    User.paginate(queryCondition, { page: page, limit: limit }, function(err, result) {
        result.rows = result.docs;
        delete result.docs;

       res.json(result)
    });
}